<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { noQueryApi } from '@/api/warehousingentry/warehousing'

// 弹窗状态
const dialogVisible = ref(false)
const selectType = ref('')

// 操作类型 (1: 组合加工, 2: 拆分加工)
const operationType = ref(null)

// 搜索表单
const searchForm = reactive({
  warehouseName: '',
  locationCode: '',
  skuName: '',
  specCode: ''
})

// 表格数据
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 选中的数据
const selectedRows = ref([])

// 打开弹窗
const open = (type, opType = null) => {
  selectType.value = type
  operationType.value = opType // 保存操作类型
  dialogVisible.value = true
  fetchData()
}

// 关闭弹窗
const closeDialog = () => {
  dialogVisible.value = false
}

// 搜索数据
const searchData = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  fetchData()
}

// 获取数据
const fetchData = async () => {
  const res = await noQueryApi(currentPage.value, pageSize.value)
  tableData.value = res.rows
  total.value = res.total
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 处理选择变化
const handleSelectionChange = (val) => {
  // 判断是否为拆分操作（只允许选择一个来源商品）
  if (operationType.value === 2) {
    // 拆分操作：如果选择多个，只保留最后一个选中的项
    if (val.length > 1) {
      // 获取最新选中的项（数组中的最后一个）
      const latestSelected = val[val.length - 1]
      // 清除其他选择
      selectedRows.value = [latestSelected]

      // 手动更新表格选择状态
      // 先清除所有选择
      tableData.value.forEach(row => {
        tableRef.value?.toggleRowSelection(row, false)
      })
      // 再选中最新项
      tableRef.value?.toggleRowSelection(latestSelected, true)
    } else {
      selectedRows.value = val
    }
  } else {
    // 组合操作或其他操作：允许多选
    selectedRows.value = val
  }
}

// 确认选择
const confirm = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一项')
    return
  }
  console.log('Confirming selected rows:', selectedRows.value)
  emit('confirm', selectedRows.value)
  closeDialog()
}

// 表格引用
const tableRef = ref(null)

// 暴露方法
const emit = defineEmits(['confirm'])
defineExpose({
  open,
  closeDialog
})
</script>
<template>
  <el-dialog v-model="dialogVisible" title="库存选择框" width="55%" :close-on-click-modal="false">
    <div class="select-dialog-content">
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" label-width="80px" :inline="true">
          <el-form-item label="仓库名称">
            <el-input v-model="searchForm.warehouseName" placeholder="请输入仓库名称" />
          </el-form-item>
          <el-form-item label="库位编码">
            <el-input v-model="searchForm.locationCode" placeholder="请输入库位编码" />
          </el-form-item>
          <el-form-item label="商品名称">
            <el-input v-model="searchForm.skuName" placeholder="请输入商品名称" />
          </el-form-item>
          <el-form-item label="规格编码">
            <el-input v-model="searchForm.specCode" placeholder="请输入规格编码" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchData">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table ref="tableRef" :data="tableData" style="width: 100%" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="warehouseName" label="仓库名称" width="120" />
        <el-table-column prop="warehouseAreaLocaLocaCode" label="库位编码" width="120" />
        <el-table-column prop="ownerName" label="货主名称" width="120" />
        <el-table-column prop="skuCode" label="商品编码" width="120" />
        <el-table-column prop="skuTitle" label="商品名称" width="120" />
        <el-table-column prop="count" label="可用数量" width="120" />
        <el-table-column prop="createTime" label="入库时间" width="120" />
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
          layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">关闭</el-button>
        <el-button type="primary" @click="confirm">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.select-dialog-content {
  height: 60vh;
  overflow-y: auto;
}

.search-area {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>